package cc.shacocloud.mirage.restful.bind.support;

import cc.shacocloud.mirage.restful.HttpRequest;
import cc.shacocloud.mirage.restful.bind.ValueConstants;
import cc.shacocloud.mirage.restful.bind.annotation.PathVariable;
import cc.shacocloud.mirage.utils.MethodParameter;
import cc.shacocloud.mirage.utils.Utils;
import cc.shacocloud.mirage.utils.charSequence.StrUtil;
import io.vertx.core.Future;
import org.jetbrains.annotations.NotNull;

/**
 * 解析{@link PathVariable} 注解的方法参数
 */
public class PathVariableMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver {
    
    @Override
    public boolean supportsParameter(@NotNull MethodParameter parameter) {
        return parameter.hasParameterAnnotation(PathVariable.class);
    }
    
    @Override
    protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
        PathVariable ann = parameter.getParameterAnnotation(PathVariable.class);
        if (ann != null) return new PathVariableNamedValueInfo(ann);
        
        throw new IllegalStateException("不支持处理当前方法，请先执行 supportsParameter 方法进行判断：" + Utils.methodDescription(parameter.getDeclaringClass(), parameter.getMethod()));
    }
    
    @Override
    protected Future<Object> resolveName(String name, MethodParameter parameter, @NotNull HttpRequest request) {
        String param = request.pathParam(name);
        
        if (StrUtil.isNotBlank(param)) {
            return Future.succeededFuture(param);
        }
        
        return Future.succeededFuture();
    }
    
    private static class PathVariableNamedValueInfo extends NamedValueInfo {
        
        public PathVariableNamedValueInfo(@NotNull PathVariable annotation) {
            super(annotation.name(), true, ValueConstants.DEFAULT_NONE);
        }
        
    }
    
}
